# coding=utf-8
import logging
import threading

from django.shortcuts import render
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.http import HttpResponseRedirect
import spider.models as spider_models
from spider.spider_selenium.spider_main_selenium import SpiderMain
from spider.layui_tools.layui_table import LayuiTableMsg
import json
from spider.models import *
import auto_sale.models as auto_sale_models
import traceback


logging.basicConfig(level=logging.INFO)


def index(request):
    logging.info('进入index')
    spider_thread = threading.Thread(target=run_spider)
    spider_thread.start()
    return render(request, 'spider/index.html')


# 管理爬取店铺
def manage_shop(request):
    return render(request, 'spider/manage_shop.html')


# 得到商品table数据
def get_shop_table_msg(request):
    shop_list = spider_models.Shop.objects.all()
    layui_table_msg = LayuiTableMsg(shop_list)
    return HttpResponse(layui_table_msg.to_json_string(), content_type="application/json")


def edit_shop(request):
    shop_id = request.GET.get('shop_id', None)
    shop_name = request.GET.get('shop_name', None)
    shop_url = request.GET.get('shop_url', None)
    # models.py中的类型不能覆盖构造函数
    # shop = Shop(shopId, shopName, shopUrl)

    # 如何利用传过来的参数呢，重新查岂不是不如只传id？？？？？？
    shop = Shop.objects.get(id=shop_id)

    logging.info('编辑店铺 shop_id=' + shop_id + ' shop_name=' + shop_name.encode('utf-8') + ' shop_url=' + shop_url)
    return render(request, 'spider/edit_shop_layer.html', {'shop': shop})


def create_shop(request):
    if request.method == 'GET':
        return render(request, 'spider/create_shop_layer.html')
    elif request.method == 'POST':
        shop_name = request.POST.get('shop_name', None)
        shop_url = request.POST.get('shop_url', None)
        Shop.objects.create(name=shop_name, url=shop_url)

        return HttpResponse('hello', content_type='text')


# 更新店铺列表
def update_shop(request):
    if request.method == 'GET':
        shop_id = request.GET.get('shop_id', None)
        shop_name = request.GET.get('shop_name', None)
        shop_url = request.GET.get('shop_url', None)
        # models.py中的类型不能覆盖构造函数
        # shop = Shop(shopId, shopName, shopUrl)

        # 如何利用传过来的参数呢，重新查岂不是不如只传id？？？？？？
        shop = Shop.objects.get(id=shop_id)

        logging.info('编辑店铺 shop_id=' + shop_id + ' shop_name=' + shop_name.encode('utf-8') + ' shop_url=' + shop_url)
        return render(request, 'spider/edit_shop_layer.html', {'shop': shop})
    elif request.method == 'POST':
        shop_id = request.POST.get('shop_id', None)
        shop_name = request.POST.get('shop_name', None)
        shop_url = request.POST.get('shop_url', None)

        shop = Shop.objects.get(id=shop_id)
        shop.name = shop_name
        shop.url = shop_url
        shop.save()

        logging.info('更新店铺 shopId=' + str(shop_id) + ' shop_name=' + shop_name + ' shop_url=' + shop_url)

        return HttpResponse('hello', content_type='text')


# 删除店铺
def delete_shop(request):
    shop_id = request.GET.get('shop_id', '100')
    Shop.objects.get(id=shop_id).delete()

    msg = '{"msg": "success"}'
    return HttpResponse(msg, content_type='application/json')


def show_product_list_in_edit_page(request):
    shop_id = int(request.GET.get('shop_id'))

    shop = Shop.objects.get(id=shop_id)
    product_list = Product.objects.filter(shop=shop)
    all_product_list_in_edit_page_html = render_to_string('spider/product_list_in_edit_page.html', {'product_list': product_list})

    auto_sale_shop_tuple = auto_sale_models.Shop.objects.get_or_create(name=shop.name, url=shop.url, spider_shop_id=shop.id)
    published_product_list = auto_sale_models.Product.objects.filter(shop=auto_sale_shop_tuple[0])
    published_product_list_in_edit_page_html = render_to_string('spider/published_product_list_in_edit_page.html', {'product_list': published_product_list})

    product_list_in_edit_page_html_dict = {'all_product_list_in_edit_page_html':all_product_list_in_edit_page_html,
                                           'published_product_list_in_edit_page_html':published_product_list_in_edit_page_html}

    return HttpResponse(json.dumps(product_list_in_edit_page_html_dict), content_type='application/json')


# 编辑爬取商品
def create_or_edit_product(request):
    action = request.GET.get('action')
    product_id = request.GET.get('product_id')

    product = ''
    size_list = []
    color_list = []
    booth_image_list = []
    detail_image_list = []
    if action == 'create':
        product = Product.objects.get(id=product_id)

        size_list = Size.objects.filter(product=product)
        color_list = Color.objects.filter(product=product)
        booth_image_list = BoothImage.objects.filter(product=product)
        detail_image_list = DetailImage.objects.filter(product=product)

    elif action == 'edit':
        product = auto_sale_models.Product.objects.get(id=product_id)

        size_list = auto_sale_models.Size.objects.filter(product=product)
        color_list = auto_sale_models.Color.objects.filter(product=product)
        booth_image_list = auto_sale_models.BoothImage.objects.filter(product=product)
        detail_image_list = auto_sale_models.DetailImage.objects.filter(product=product)

    return render(request, 'spider/edit_product.html',
                  {'product': product, 'size_list': size_list, 'color_list': color_list,
                   'booth_image_list': booth_image_list, 'detail_image_list': detail_image_list, 'action':action})


def update_product_list_image(request):
    product_id = request.POST.get('product_id')
    product_list_image_url = request.POST.get('product_list_image_url')

    product = Product.objects.get(id=product_id)
    product.image = product_list_image_url
    product.save()
    logging.info('update product_list_image product_id=' + product_id)
    # return HttpResponse(json.dumps({'result': 'success'}), content_type='application/json')
    return HttpResponse('success', content_type='text')


def add_product_booth_and_detail_image(request):
    image_site = request.POST.get('image_site')
    image_net_url = request.POST.get('image_net_url')
    product_id = request.POST.get('product_id')
    product = Product.objects.get(id=product_id)
    image_id = 0
    if image_site == 'booth_image':

        if len(BoothImage.objects.filter(product=product, net_path=image_net_url)) != 0:
            return HttpResponse(json.dumps({'result': 'exist'}), content_type='application/json')
        else:
            BoothImage.objects.create(product=product, local_path='', net_path=image_net_url)
            logging.info('add booth_image image_net_url=' + image_net_url)
            image_id = len(BoothImage.objects.filter(product=product)) - 1

    elif image_site == 'detail_image':
        if len(DetailImage.objects.filter(product=product, net_path=image_net_url)) != 0:
            return HttpResponse(json.dumps({'result': 'exist'}), content_type='application/json')
        else:
            DetailImage.objects.create(product=product, local_path='', net_path=image_net_url)
            logging.info('add detail_image image_net_url=' + image_net_url)
            image_id = len(DetailImage.objects.filter(product=product)) - 1

    return HttpResponse(json.dumps({'res': 'success', 'image_id': image_id}), content_type='application/json')


def publish_product(request):
    try:
        action = request.POST.get('action')
        logging.info('action=' + action)
        product_id = request.POST.get('product_id')
        logging.info('type(product_id)=' + str(type(product_id)))
        product = Product.objects.get(id=product_id)
        if action == 'create':

            # 建立商城的product
            # auto_sale_product = auto_sale_models.Product.objects.get_or_create(name=product.product_name, url=product.product_url,
            #                                                price=product.product_price, count=product.product_count,
            #
            #                                              image=product.product_image, spider_product_id=product.id)

            # 建立商城的shop 试试是否可以product.shop_id
            shop = Shop.objects.get(id=product.shop.id)
            auto_sale_shop_tuple = auto_sale_models.Shop.objects.get_or_create(name=shop.name, url=shop.url, spider_shop_id=shop.id)
            auto_sale_shop = auto_sale_shop_tuple[0]

            # 建立商城的product
            auto_sale_product_tuple = auto_sale_models.Product.objects.get_or_create(url=product.url,
            spider_product_id=product.id, shop=auto_sale_shop)
            auto_sale_product = auto_sale_product_tuple[0]
            # logging.info('type(auto_sale_product[0])=' + str(type(auto_sale_product[0])))
            auto_sale_product.name = request.POST.get('product_name')
            auto_sale_product.price = request.POST.get('product_price')

            auto_sale_product.count = product.count
            auto_sale_product.image = product.image
            auto_sale_product.save()

            color_list = Color.objects.filter(product=product)
            for index, color in enumerate(color_list):
                color_another_name_tag_name = "color_another_name_" + str(index)
                color_checkbox_tag_name = "color_checkbox_" + str(index)

                color.another_name = request.POST.get(color_another_name_tag_name)
                color_checkbox = request.POST.get(color_checkbox_tag_name)
                if (color_checkbox == 'on'):
                    color.is_valid = True
                else:
                    color.is_valid = False

                color.save()
                # 建立商城的color
                auto_sale_color_tuple = auto_sale_models.Color.objects.get_or_create(spider_color_id=color.id,
                                                                                     product=auto_sale_product)
                auto_sale_color = auto_sale_color_tuple[0]
                auto_sale_color.name = color.another_name
                auto_sale_color.is_valid = color.is_valid
                auto_sale_color.save()

            size_list = Size.objects.filter(product=product)
            for index, size in enumerate(size_list):
                size_another_name_tag_name = "size_another_name_" + str(index)
                size_checkbox_tag_name = "size_checkbox_" + str(index)

                size.another_name = request.POST.get(size_another_name_tag_name)
                size_checkbox = request.POST.get(size_checkbox_tag_name)
                if (size_checkbox == 'on'):
                    size.is_valid = True
                else:
                    size.is_valid = False

                size.save()

                # 建立商城的size
                auto_sale_size_tuple = auto_sale_models.Size.objects.get_or_create(spider_size_id=size.id,
                                                                                   product=auto_sale_product)
                auto_sale_size = auto_sale_size_tuple[0]
                auto_sale_size.name = size.another_name
                auto_sale_size.is_valid = size.is_valid
                auto_sale_size.save()

            booth_image_list = BoothImage.objects.filter(product=product)
            for index, booth_image in enumerate(booth_image_list):
                booth_image_checkbox_tag_name = "booth_image_checkbox_" + str(index)
                booth_image_checkbox = request.POST.get(booth_image_checkbox_tag_name)
                if (booth_image_checkbox == 'on'):
                    booth_image.is_valid = True
                else:
                    booth_image.is_valid = False

                booth_image.save()

                # 建立商城的booth_image
                auto_sale_booth_image_tuple = auto_sale_models.BoothImage.objects.get_or_create(
                    spider_booth_image_id=booth_image.id,
                    product=auto_sale_product)
                auto_sale_booth_image = auto_sale_booth_image_tuple[0]
                auto_sale_booth_image.local_path = booth_image.local_path
                auto_sale_booth_image.net_path = booth_image.net_path
                auto_sale_booth_image.is_valid = booth_image.is_valid
                auto_sale_booth_image.save()

            detail_image_list = DetailImage.objects.filter(product=product)
            for index, detail_image in enumerate(detail_image_list):
                detail_image_checkbox_tag_name = "detail_image_checkbox_" + str(index)
                # detail_img_checkbox_23
                detail_image_checkbox = request.POST.get(detail_image_checkbox_tag_name)
                if (detail_image_checkbox == 'on'):
                    detail_image.is_valid = True
                else:
                    detail_image.is_valid = False

                detail_image.save()

                # 建立商城的detail_image
                auto_sale_detail_image_tuple = auto_sale_models.DetailImage.objects.get_or_create(
                    spider_detail_image_id=detail_image.id,
                    product=auto_sale_product)

                auto_sale_detail_image = auto_sale_detail_image_tuple[0]
                auto_sale_detail_image.local_path = detail_image.local_path
                auto_sale_detail_image.net_path = detail_image.net_path
                auto_sale_detail_image.is_valid = detail_image.is_valid
                auto_sale_detail_image.save()

            # 建立商城的inventory
            inventory_list = Inventory.objects.filter(product=product)
            for inventory in inventory_list:
                auto_sale_size = auto_sale_models.Size.objects.get(spider_size_id=inventory.size.id,
                                                                   product=auto_sale_product)
                auto_sale_color = auto_sale_models.Color.objects.get(spider_color_id=inventory.color.id,
                                                                     product=auto_sale_product)
                auto_sale_inventory_tuple = auto_sale_models.Inventory.objects.get_or_create(product=auto_sale_product,
                                                                                             size=auto_sale_size,
                                                                                             color=auto_sale_color,
                                                                                             spider_inventory_id=inventory.id)
                auto_sale_inventory = auto_sale_inventory_tuple[0]
                auto_sale_inventory.count = inventory.count
                auto_sale_inventory.save()
        elif action == 'edit':
            pass
    except Exception, e:
        return HttpResponse('添加商品出现异常 traceback.format_exc()=' + traceback.format_exc(), content_type='text')

    return HttpResponseRedirect('/single/?product_id=' + str(auto_sale_product.id))

def start_crawl_all_shop_product_list(request):
    spider = SpiderMain()
    spider.craw_all_shop()

    msg = {'res': 'success'}
    return HttpResponse(json.dumps(msg), content_type='application/json' )

def crawl_one_shop_product_list(request):
    try:
        shop_id = request.GET.get('shop_id')
        logging.info('shop_id=' + shop_id)
        spider = SpiderMain()
        spider.craw_one_shop(shop_id)

        msg = {'res':'success'}
    except Exception, e:
        logging.info(e.message)
    return HttpResponse(json.dumps(msg), content_type='application/json')




# 通过thread 实现django中
# 这个放在index函数后面，居然可以调用
# 如果在类中的函数之外写代码，则一定会被执行。
def run_spider():
    spider = SpiderMain()
    spider.craw_all_shop()
